import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Data, Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { Observable } from 'rxjs/internal/Observable';
import { of } from 'rxjs/internal/observable/of';
import { catchError } from 'rxjs/internal/operators/catchError';
import { debounceTime } from 'rxjs/internal/operators/debounceTime';
import { map } from 'rxjs/internal/operators/map';
import { switchMap } from 'rxjs/internal/operators/switchMap';
import { tap } from 'rxjs/operators';
import { Model, ModelPermission, Pageable, Sysrole, SysroleModelPermissionPK, SysroleUrlPermissionPK } from 'src/app/domain/sparrow';
import { SparrowApp } from 'src/app/domain/sparrow-app';
import { ModelService } from 'src/app/service/model.service';
import { SysroleService } from 'src/app/service/sysrole.service';
import { AppSearchComponent } from 'src/app/share/app-search/app-search.component';
import { SetModelPermissionComponent } from 'src/app/share/set-model-permission/set-model-permission.component';

interface ItemData {
  name: string;
  age: number;
  address: string;
}


@Component({
  selector: 'app-model',
  templateUrl: './model.component.html',
  styleUrls: ['./model.component.css']
})
export class ModelComponent implements OnInit {

  listOfData: Model[] = [];


  constructor(private modelService: ModelService, private router: Router, private fb: FormBuilder, private sysroleService: SysroleService) { }


  httpMethods: any = [];
  urlPermissions: any = [];
  pageable: Pageable = {page: 1, size: 10}
  total: number = 0;


  // setPermission(){
  //   let ids: string[] = []
  //   ids.push("cn.sparrow.model.organization.OrganizationRelation")
  //   ids.push("cn.sparrow.model.permission.SysroleMenu")
  //   this.router.navigateByUrl(this.router.createUrlTree(["/modelPermission",{ids:JSON.stringify(ids)}]))
  // }

  validateForm!: FormGroup;
  // models$ = this.modelService.list(this.pageable).pipe(map(m=>m.content),map((a,i)=>{a[i].id=a[i].name;return a;}),tap(b=>console.log(b)));



  ngOnInit(): void {

    this.modelService.list({page: this.pageable.page-1, size: this.pageable.size}).subscribe(res => {
      this.listOfCurrentPageData = res.content;
      this.total = res.totalElements;
      console.log(this.total)
    })
  }

  checked = false;
  loading = false;
  indeterminate = false;
  // listOfData: readonly Data[] = [];
  listOfCurrentPageData: readonly Data[] = [];
  setOfCheckedId = new Set<string>();

  updateCheckedSet(id: string, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onCurrentPageDataChange(listOfCurrentPageData: readonly Data[]): void {
    this.listOfCurrentPageData = listOfCurrentPageData;
    this.refreshCheckedStatus();

  }
  onPageIndexChange(page: number) {
    this.pageable.page = page;
    this.modelService.list(this.pageable).subscribe(res => {
      this.total = res.totalElements;
      this.listOfCurrentPageData = res.content;
      this.setOfCheckedId.clear()
      // this.listOfData = res.content;
    })
  }

  onPageSizeChange(size: number) {
    this.pageable.size = size;
    this.modelService.list(this.pageable).subscribe(res => {
      this.total = res.totalElements;
      this.listOfCurrentPageData = res.content;
      this.setOfCheckedId.clear()
      // this.listOfData = res.content;
    })
  }

  refreshCheckedStatus(): void {
    const listOfEnabledData = this.listOfCurrentPageData.filter(({ disabled }) => !disabled);
    this.checked = listOfEnabledData.every(({ id }) => this.setOfCheckedId.has(id));
    this.indeterminate = listOfEnabledData.some(({ id }) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  onItemChecked(id: string, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(checked: boolean): void {
    this.listOfCurrentPageData
      // .filter(({ system }) => !system)
      .forEach(({ name }) => this.updateCheckedSet(name, checked));
    this.refreshCheckedStatus();
  }

  onDelete() {
    console.log(Array.from(this.setOfCheckedId));
    this.modelService.delete(Array.from(this.setOfCheckedId)).subscribe(res => {
      this.modelService.list(this.pageable).subscribe(res => {
        this.total = res.totalElements;
        this.listOfCurrentPageData = res.content;
        // this.listOfData = res.content;
      })
    });
    console.log(this.setOfCheckedId)
    this.refreshCheckedStatus();
  }




  isVisible = false;

  showModal(): void {
    let url: Model;
    this.isVisible = true;
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      uri: [null, [Validators.required]],
      method: [null, [Validators.required]],
      permission: [null, [Validators.required]],
      clientId: [null, [Validators.required]],
    });
  }




  handleOk(): void {
    console.log('Button ok clicked!');
    // for (const i in this.validateForm.controls) {
    //   console.log(this.validateForm.value)
    // }
    this.isVisible = false;
    this.modelService.save(this.validateForm.value).subscribe(res => {

    })
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isNewVisible = false;
    this.isVisibleForSetPermission = false;

  }

  @ViewChild(AppSearchComponent) appSearch!:AppSearchComponent;
  submitForm(): void {
    if (!this.validateForm.valid) {
      for (const i in this.validateForm.controls) {
        if (this.validateForm.controls.hasOwnProperty(i)) {
          this.validateForm.controls[i].markAsDirty();
          this.validateForm.controls[i].updateValueAndValidity();
        }
      }
    } else {
      let app: Model = this.validateForm.value
      app.appId = this.appSearch.selectedUser![0].id
      this.modelService.save(app).subscribe(res => {
        this.isNewVisible = false;
      })
    }
  }

  onClose() {

  }

  handlePermissionCancel() {
    this.isVisibleForPermission = false;
  }

  // for permission
  randomUserUrl = 'https://api.randomuser.me/?results=5';
  searchChange$ = new BehaviorSubject('');
  optionList: Sysrole[] = [];
  selectedUser?: Sysrole[];
  isLoading = false;

  onSearch(value: string): void {
    this.isLoading = true;
    this.searchChange$.next(value);
  }
  isVisibleForPermission = false;

  selected: Model[] | any = [];

  setPermission() {
    const modelNames$ = this.listOfCurrentPageData.filter(f => this.setOfCheckedId.has(f.id)).map(m => m.name);
    console.log(modelNames$)
    this.router.navigateByUrl(this.router.createUrlTree(["/modelPermission", { ids: JSON.stringify(modelNames$) }]));

  }

  addPermission() {
    let modelPermission!: ModelPermission;
    let pks: SysroleModelPermissionPK[] = [];
    // this.selected.forEach((url: { id: any; }) => {
    //   this.selectedUser?.forEach(user => {
    //     let pk: SysroleModelPermissionPK = {sysroleId:user.id,modelName: url.id};
    //     pk.sysroleId = user.id
    //     pk.modelName = url.id
    //     pks.push({sysroleId:user.id,modelName: url.id})
    //   })
    // });
    modelPermission.sysroleModelPermissionPKs = pks
    this.modelService.addPermission(modelPermission).subscribe(res => {
      this.isVisibleForPermission = false;
    })
  }

  delPermission() {
    let pks: SysroleUrlPermissionPK[] = [];
    this.selected.forEach((url: { id: any; }) => {
      this.selectedUser?.forEach(user => {
        let pk: SysroleUrlPermissionPK = new SysroleUrlPermissionPK();
        pk.sysroleId = user.id
        pk.urlId = url.id
        pks.push(pk)
      })
    });
    this.modelService.delPermission(pks).subscribe(res => {
      this.isVisibleForPermission = false;
    })
  }

  // currentPermissions: SysroleUrlPermission[] = [];

  // isVisibleForCheckPermission:boolean = false;
  checkUrlPermission() {
    // this.modelService.getPermissionById(Array.from(this.setOfCheckedId)).subscribe(res => {
    //   this.currentPermissions = res.content
    //   this.isVisibleForCheckPermission = true;
    // })
  }

  handleCheckPermissionCancel() {
    // this.isVisibleForCheckPermission = false;
  }


  isNewVisible = false;
  new(){
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      nameTxt: [null, [Validators.required]],
      remark: [null, null],
    });
    this.isNewVisible = true;
  }


  @ViewChild(SetModelPermissionComponent) setModelPermissionComponent!: SetModelPermissionComponent;
   isVisibleForSetPermission: boolean = false;

   showSetPermissionModal() {
    // const modelNames$ = this.setOfCheckedId.;

     this.isVisibleForSetPermission = true;
     setTimeout(() => {
      this.setOfCheckedId.forEach(f=>{
        this.setModelPermissionComponent.models.push({name: f, nameTxt: f});
      })
     })
   }

   saveModelPermission() {
     this.setModelPermissionComponent.addPermission();
     this.isVisibleForSetPermission = false;
   }
}
